package com.letv.android.client.webview;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Handler;
import android.view.View;
import android.webkit.WebView;

import com.letv.core.listener.OnRelevantStateChangeListener;
import com.letv.core.utils.LogInfo;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author liuxx
 *         android与js交互的类
 *         注：1. android4.4以上不允许使用静态方法
 *         2. api 19 支持 “evaluateJavascript (String script, ValueCallback<String> resultCallback)” 方法
 *         3. 4.2以下会存在JS交互漏洞问题，4.2以上可通过加注解解决
 *         4.每个WebViewActivity对象都对应一个JavaScriptinterface对象
 */
@SuppressLint("NewApi")
public class JavaScriptinterface implements
         OnRelevantStateChangeListener,
        NetWorkChangeObserver
{
    private static final String RESULT_SUCCEED = "{\"result\": 200}";
    private static final String RESULT_FAIL = "{\"result\": 400}";
    private static final String RESULT_CANNELED = "{\"result\": 201}";
    private static final String TAG = "JavaScriptinterface";
    private static Activity mActivity;
    private static JavaScriptinterface javaScriptinterface;
    private static JSInBean jsInBean;
    private static WebView mWebView;
    private static List<String> methods = new ArrayList<String>();
    private Handler handler;
    private PayCallBack payCallBack;
    private Handler activityHandler;
    private View root;

    public JavaScriptinterface() {
    }

    public JavaScriptinterface(Activity activity, WebView webView, View root) {
        mActivity = activity;
        mWebView = webView;
        addAllMethods();
//        SignSharePageActivity.observers.add(0, this);
//        WXEntryActivity.observers.add(0, this);
//        SharePageActivity.observers.add(0, this);
//        LetvQZoneShare.observers.add(0, this);
        NetWorkBroadcastReceiver.registerObserver(this);
//        URIResultHandler.setURIResultListener(this, true);
        handler = new Handler(mActivity.getMainLooper());
        this.root = root;
    }

    public void removeAllObservers() {
//        SignSharePageActivity.observers.remove(this);
//        WXEntryActivity.observers.remove(this);
//        SharePageActivity.observers.remove(this);
//        LetvQZoneShare.observers.remove(this);
        NetWorkBroadcastReceiver.unRegisterObserver(this);
//        URIResultHandler.removeURIResultListener(this, false);
    }

    public void setHandler(Handler handler) {
        activityHandler = handler;
    }

    private static void addAllMethods() {
        methods.add("core.hasFeature");
        methods.add("fun.callShare");
        methods.add("fun.setShare");
        methods.add("fun.callLogin");
        methods.add("fun.callLogout");
        methods.add("fun.playVideo");
        methods.add("fun.callWebview");
        methods.add("core.getPcode");
        methods.add("core.getVersion");
        methods.add("fun.setStatus");
        methods.add("fun.callAlert");
        methods.add("core.getUserInfo");
        methods.add("core.getDeviceInfo");
        methods.add("core.getNetworkState");
        methods.add("core.getPowerLevel");
        methods.add("fun.callBrowser");
        methods.add("core.getOnlineDevice");
        methods.add("fun.callScanCode");
        methods.add("fun.saveVideo");
    }

    public interface PayCallBack {
        void onPaySuccessed();

        void onPayFailed();
    }

    /**
     * 组成调用JS方法的字符串，供loadUrl使用
     *
     * @param funcName   JS的方法名
     * @param callbackId
     * @param result     返回给JS的Json串
     * @return
     */
    public static String buildupJSCallString(String funcName, String callbackId, String result) {
//      javascript:LetvJSBridge.fireEvent('letv_bridge_1406795025490621','true')
        StringBuilder builder = new StringBuilder();
        builder.append("javascript:");
        builder.append(funcName);
        builder.append("(");
        builder.append("'" + callbackId + "'");
        builder.append(",");
        builder.append("'" + result + "'");
        builder.append(");");
        return builder.toString();
    }

    @Override
    public void onTimeChange() {

    }

    @Override
    public void onNetChange() {
        //把一启动的网络状态持久化，然后onNetChange之后再获取一次Net状态
        LogInfo.log("lxx", "onNetChange");
    }

    @Override
    public void onBatteryChange(int curStatus, int curPower) {
        LogInfo.log("lxx", "onBatteryChange, curStatus: " + curStatus + ", curPower: " + curPower);
    }

    @Override
    public void onDownloadStateChange() {

    }

    @Override
    public void onHeadsetPlug() {

    }

    @Override
    public void onNetTypeChange(HashMap<String, Object> netMap) {
        String callString = "javascript:LetvJSBridge.fireEvent('onNetworkChange','" + (new JSONObject(netMap)).toString() + "')";
        LogInfo.log("lxx", "onNetTypeChange callString: " + callString);
        mWebView.loadUrl(callString);
    }
}